package com.zhaopin.utils;

import java.io.File;
import java.io.IOException;

public class PathUtil {

    public static String formatPath(String path) {
        if (path.endsWith("/") || path.endsWith("\\"))
            path = path.substring(0, path.length() - 1);

        return path.replace("\\", "/");
    }

    public static String convertPath(String path) {
        path = formatPath(path);

        if (path.startsWith("/"))
            path = path.substring(1);

        return path.replace("/", "_");
    }

    public static String getProjectRoot(Class clazz) throws IOException {
        String path;
        File file = new File("");

        String p = file.getCanonicalPath();
        if (p.endsWith("bin")) {
            path = formatPath(p).replace("/bin", "");
        } else {
            path = clazz.getClassLoader().getResource("application.yml").getPath();
            if (path.startsWith("file")) {
                path = path.replace("file:", "");
                String[] ps = path.split("/");
                path = "/" + ps[1] + "/" + ps[2];
            } else
                path = formatPath(path).replace("/resources/main/application.yml", "");
        }

        return path;
    }

    public static String replacePath(String path, String replace) {
        if (path.startsWith("/"))
            path = path.substring(1);

        if (replace.startsWith("/"))
            replace = replace.substring(1);

        return path.replace(replace, "");
    }

    public static String neatPath(String path) {
        if (null == path)
            return path;

        if (path.endsWith("/"))
            path = path.substring(0, path.length() - 1);

        if (!path.startsWith("/"))
            path = "/" + path;

        return path;
    }
}
